package com.yonyou.distribute.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * p19  redis 演示超卖
 *
 * 解决方案：
 * 1、jvm本地锁
 * 2、redis乐观锁  watch: multi exec
 * 3、分布式锁
 */
@Slf4j
@Service
public class RedisService_1 {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    private Integer port;

    public void deduct() {
        // 1、查询库存
        String stock = this.stringRedisTemplate.opsForValue().get("stock");
        // 2、判断库存是否充足
        if(!StringUtils.isEmpty(stock)){
            Integer st = Integer.valueOf(stock);
            if(st > 0){
                //3、更新库存到数据库
                this.stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
            }
        }
    }
}
